import { _decorator, Component, director, SceneAsset, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('SceneManager')
export class SceneManager extends Component {
    // 预加载场景资源
    public preloadScene(sceneName: string, progressCallback?: (completedCount: number, totalCount: number, item: any) => void, completeCallback?: (error: Error | null, asset: SceneAsset) => void) {
        director.preloadScene(sceneName, progressCallback, (error: Error | null, asset: SceneAsset) => {
            if (error) {
                console.error('场景预加载失败:', error);
                completeCallback?.(error, null);
                return;
            }
            console.log('场景预加载成功:', sceneName);
            completeCallback?.(null, asset);
        });
    }

    // 带加载进度的场景切换
    public switchSceneWithLoading(sceneName: string, loadingNode: Node) {
        // 显示加载界面
        loadingNode.active = true;

        // 预加载场景
        this.preloadScene(sceneName, (completedCount, totalCount) => {
            // 更新加载进度
            const progress = completedCount / totalCount;
            this.updateLoadingProgress(progress);
        }, (error) => {
            if (error) {
                loadingNode.active = false;
                return;
            }

            // 场景加载完成后切换
            director.loadScene(sceneName, () => {
                // 隐藏加载界面
                loadingNode.active = false;
                console.log('场景切换完成:', sceneName);
            });
        });
    }

    // 直接切换场景(新增方法)
    public switchScene(sceneName: string) {
        director.loadScene(sceneName, (error: Error | null) => {
            if (error) {
                console.error('场景切换失败:', error);
                return;
            }
            console.log('场景切换成功:', sceneName);
        });
    }

    // 更新加载进度显示
    private updateLoadingProgress(progress: number) {
        // 这里可以更新进度条或其他UI元素
        console.log('加载进度:', progress * 100, '%');
    }
}